<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kylin</title><meta name="keywords" content="学习，博客，技术交流，学习记录，Kylin，kylin"><meta name="author" content="Kylin"><meta name="copyright" content="Kylin"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="学习不易，努力努力~">
<meta property="og:type" content="website">
<meta property="og:title" content="Kylin">
<meta property="og:url" content="https://www.codekylin.cn/page/28/index.html">
<meta property="og:site_name" content="Kylin">
<meta property="og:description" content="学习不易，努力努力~">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://qiniu.codekylin.cn/img/20200807181526.jpg">
<meta property="article:author" content="Kylin">
<meta property="article:tag" content="学习，博客，技术交流，学习记录，Kylin，kylin">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://qiniu.codekylin.cn/img/20200807181526.jpg"><link rel="shortcut icon" href="https://qiniu.codekylin.cn/img/20200807181548.png"><link rel="canonical" href="https://www.codekylin.cn/page/28/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.google-analytics.com" crossorigin=""/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><meta name="google-site-verification" content="gzeyWstt6NoTZKh7YFYNLNziL8HIZ8YH2Ug7xTDX5-Y"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?f76c34daefe747deee7c7be3ead2ba80";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script async="async" src="https://www.googletagmanager.com/gtag/js?id=UA-159334016-1"></script><script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-159334016-1');
</script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: {"limitDay":90,"position":"top","messagePrev":"自上次更新以来已经","messageNext":"天，文章的内容可能已过时或存在差异。"},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50000,"languages":{"author":"作者: Kylin","link":"链接: ","source":"来源: Kylin","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#FF0000","bgDark":"#2d3035","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: false,
  isHome: true,
  isHighlightShrink: false,
  isToc: false,
  postUpdate: '2022-10-12 21:14:27'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
          const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
          const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
          const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified

          if (t === undefined) {
            if (isLightMode) activateLightMode()
            else if (isDarkMode) activateDarkMode()
            else if (isNotSpecified || hasNoSupport) {
              const now = new Date()
              const hour = now.getHours()
              const isNight = hour <= 6 || hour >= 18
              isNight ? activateDarkMode() : activateLightMode()
            }
            window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
              if (saveToLocal.get('theme') === undefined) {
                e.matches ? activateDarkMode() : activateLightMode()
              }
            })
          } else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><link rel="stylesheet" href="https://qiniu.codekylin.cn/github/img/img/custom.css"><link rel="stylesheet" href="//at.alicdn.com/t/font_1993646_z05rabxf05h.css"><link rel="stylesheet" href="https://qiniu.codekylin.cn/github/img/img/icon.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Kylin" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" data-lazy-src="https://qiniu.codekylin.cn/img/20200807181526.jpg" onerror="onerror=null;src='https://qiniu.codekylin.cn/github/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">362</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">427</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">101</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="page" id="body-wrap"><header class="full_page" id="page-header" style="background-image: url('https://qiniu.codekylin.cn/github/img/img20201017211426.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Kylin</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="site-info"><h1 id="site-title">Kylin</h1><div id="site-subtitle"><span id="subtitle"></span></div><div id="site_social_icons"><a class="social-icon" href="https://github.com/kylincw" target="_blank" title="Github"><i class="iconfont icon-github"></i></a><a class="social-icon" href="tencent://message/?Menu=yes&amp;uin=171346168&amp;Service=300&amp;sigT=45a1e5847943b64c6ff3990f8a9e644d2b31356cb0b4ac6b24663a3c8dd0f8aa12a595b1714f9d45" target="_blank" title="qq"><i class="iconfont icon-qq"></i></a><a class="social-icon" href="https://space.bilibili.com/53836035" target="_blank" title="BiliBili"><i class="iconfont icon-bilibili-line"></i></a><a class="social-icon" href="mailto:zhang171346168@qq.com" target="_blank" title="Email"><i class="iconfont icon-email1"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS"><i class="iconfont icon-rss"></i></a></div></div><div id="scroll-down"><i class="fas fa-angle-down scroll-down-effects"></i></div></header><main class="layout" id="content-inner"><div class="recent-posts" id="recent-posts"><div class="recent-post-item"><div class="post_cover left_radius"><a href="/57545.html" title="MyBatis学习-10">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-0pvrpm.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MyBatis学习-10"></a></div><div class="recent-post-info"><a class="article-title" href="/57545.html" title="MyBatis学习-10">MyBatis学习-10</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2019-10-30T12:40:26.000Z" title="发表于 2019-10-30 20:40:26">2019-10-30</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/SSM/">SSM</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/SSM/MyBatis/">MyBatis</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/57545.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/57545.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">MyBatis运行原理运行过程中涉及到的类

ResourcesMyBatis 中 IO 流的工具类
加载配置文件


SqlSessionFactoryBuilder() 构建器
作用:创建 SqlSessionFactory 接口的实现类


XMLConfigBuilder MyBatis 全局配置文件内容构建器类
作用负责读取流内容并转换为 JAVA 代码.


Configuration 封装了全局配置文件所有配置信息.
全局配置文件内容存放在 Configuration 中


DefaultSqlSessionFactory 
是SqlSessionFactory接口的实现类


Transaction 事务类
每一个 SqlSession 会带有一个 Transaction 对象.


TransactionFactory 事务工厂
负责生产 Transaction


Executor MyBatis 执行器
作用:负责执行 SQL 命令
相当于 JDBC 中 statement 对象(或 PreparedStatement或 CallableStatement)
默 ...</div></div></div><div class="recent-post-item"><div class="post_cover right_radius"><a href="/20046.html" title="MyBatis学习-9">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-2k8wlg.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MyBatis学习-9"></a></div><div class="recent-post-info"><a class="article-title" href="/20046.html" title="MyBatis学习-9">MyBatis学习-9</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2019-10-30T12:17:59.000Z" title="发表于 2019-10-30 20:17:59">2019-10-30</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/SSM/">SSM</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/SSM/MyBatis/">MyBatis</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/20046.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/20046.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">MyBatis 注解注解:为了简化配置文件.Mybatis 的注解简化 mapper.xml 文件.
如果涉及动态 SQL 依然使用 mapper.xml
mapper.xml 和注解可以共存.
使用注解时 mybatis.xml 中&lt;-mappers&gt;使用&lt;-package/&gt;或者&lt;-mapper class=””/&gt;

实现查询实现新增实现修改实现删除使用注解通过AutoMapping结合别名实现多表查询

使用注解实现&lt;-resultMap&gt;功能（不推荐使用）
以 N+1 举例
在 StudentMapper 接口添加查询  
在 TeacherMapper 接口添加
@Results() 相当于&lt;-resultMap&gt;
@Result() 相当于&lt;-id/&gt;或&lt;-result/&gt;
@Result(id=true) 相当与&lt;-id/&gt;
@Many() 相当于&lt;-collection/&gt;
@One() 相当于&lt;-association/&gt;





</div></div></div><div class="recent-post-item"><div class="post_cover left_radius"><a href="/36495.html" title="MyBatis学习-8">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/images/20200601091329.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MyBatis学习-8"></a></div><div class="recent-post-info"><a class="article-title" href="/36495.html" title="MyBatis学习-8">MyBatis学习-8</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2019-10-30T10:24:54.000Z" title="发表于 2019-10-30 18:24:54">2019-10-30</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/SSM/">SSM</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/SSM/MyBatis/">MyBatis</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/36495.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/36495.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">MyBatis多表查询
实现多表查询方式
业务装配.对两个表编写单表查询语句,在业务(Service)把查询的两个结果进行关联.
使用AutoMapping特性,在实现两表联合查询时通过别名完成映射.
使用 MyBatis 的标签进行实现.


多表查询时,类中包含另一个类的对象的分类
单个对象
集合对象resultMap 标签



&lt;-resultMap&gt;标签写在mapper.xml中,由程序员控制SQL查询结果与实体类的映射关系.
默认 MyBatis 使用 AutoMapping 特性.
使用&lt;-resultMap&gt;标签时,&lt;-select&gt;标签不写 resultType 属性,而是使用 resultMap 属性引用&lt;-resultMap&gt;标签.
使用 resultMap 实现单表映射关系
数据库设计


实体类设计

TeacherMapper.xml代码


resultMap 实现关联单个对象(N+1 方式)N+1 查询方式,先查询出某个表的全部信息,根据这个表的信息查询另一个表的信息.

&lt;-association& ...</div></div></div><div class="recent-post-item"><div class="post_cover right_radius"><a href="/35535.html" title="MyBatis学习-7">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-4xlkjz.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MyBatis学习-7"></a></div><div class="recent-post-info"><a class="article-title" href="/35535.html" title="MyBatis学习-7">MyBatis学习-7</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2019-10-30T04:45:49.000Z" title="发表于 2019-10-30 12:45:49">2019-10-30</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/SSM/">SSM</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/SSM/MyBatis/">MyBatis</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/35535.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/35535.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">缓存应用程序和数据库交互的过程是一个相对比较耗时的过程。缓存存在的意义:让应用程序减少对数据库的访问,提升程序运行效率

MyBatis 中默认 SqlSession 缓存开启

同一个 SqlSession 对象调用同一个&lt;-select&gt;时,只有第一次访问数据库,第一次之后把查询结果缓存到 SqlSession 缓存区(内存)中
缓存的是 statement 对象.–简单记忆。(必须是用一个&lt;-select&gt;增删改都没有数据库数据返回)
在 myabtis 时一个&lt;-select&gt;对应一个 statement 对象
有效范围必须是同一个 SqlSession 对象


缓存流程

步骤一: 先去缓存区中找是否存在 statement
步骤二:返回结果
步骤三:如果没有缓存 statement 对象,去数据库获取数据
步骤四:数据库返回查询结果
步骤五:把查询结果放到对应的缓存区中
SqlSessionFactory 缓存(二级缓存)



有效范围:同一个 factory 内哪个 SqlSession 都可以获取

什么时候使用二级缓存:
当数据 ...</div></div></div><div class="recent-post-item"><div class="post_cover left_radius"><a href="/18958.html" title="MyBatis学习-6">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-3kp6yv.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MyBatis学习-6"></a></div><div class="recent-post-info"><a class="article-title" href="/18958.html" title="MyBatis学习-6">MyBatis学习-6</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2019-10-30T02:15:12.000Z" title="发表于 2019-10-30 10:15:12">2019-10-30</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/SSM/">SSM</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/SSM/MyBatis/">MyBatis</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/18958.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/18958.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">ThreadLocal（jdk中）线程容器,给线程绑定一个 Object 内容,后只要线程不变,可以随时取出.改变线程,无法取出内容.


1234567final ThreadLocal&lt;String&gt; threadLocal = new ThreadLocal&lt;&gt;();threadLocal.set(&quot;测试&quot;); new Thread()&#123;     public void run() &#123;         String result = threadLocal.get();         System.out.println(&quot;结果:&quot;+result);         &#125;;     &#125;.start();
利用这一特性优化mybatis中service加载配置文件，创建session代码
MyUtil
1234567891011121314151617181920212223242526272829303132333435363738394041424344package com ...</div></div></div><div class="recent-post-item"><div class="post_cover right_radius"><a href="/19278.html" title="MyBatis学习-5">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/deepin-4.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MyBatis学习-5"></a></div><div class="recent-post-info"><a class="article-title" href="/19278.html" title="MyBatis学习-5">MyBatis学习-5</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2019-10-30T00:23:17.000Z" title="发表于 2019-10-30 08:23:17">2019-10-30</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/SSM/">SSM</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/SSM/MyBatis/">MyBatis</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/19278.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/19278.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">动态 SQL根据不同的条件需要执行不同的 SQL 命令.称为动态 SQL
MyBatis 中动态 SQL 在 mapper.xml 中添加逻辑判断等.
OGNL 表达式,直接写 key 或对象的属性，不需要添加任何特殊符号。只能获取kye或对象的属性

If标签使用判断是否满足条件，在动态 SQL 中所做的最通用的事情是包含部分 where 字句的条件。注意：在where子句后面如果直接使用if，会造成where and···语法错误，若where后面没有条件，则需要添加一个正确的等式（例如1=1）
12345678910&lt;select id=&quot;selByAccinAccout&quot; resultType=&quot;log&quot;&gt;     select * from log where 1=1    &lt;!-- OGNL 表达式,直接写 key 或对象的属性.不需要添加任 何特字符号 --&gt;     &lt;if test=&quot;accin!=null and accin!=&#x27;&#x27;&quot;&gt;         ...</div></div></div><div class="recent-post-item"><div class="post_cover left_radius"><a href="/35727.html" title="MyBatis学习-4">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-nekg9l.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MyBatis学习-4"></a></div><div class="recent-post-info"><a class="article-title" href="/35727.html" title="MyBatis学习-4">MyBatis学习-4</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2019-10-29T12:28:29.000Z" title="发表于 2019-10-29 20:28:29">2019-10-29</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/SSM/">SSM</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/SSM/MyBatis/">MyBatis</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/35727.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/35727.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">MyBatis 接口绑定作用:实现创建一个接口后，把mapper.xml变成由mybatis生成接口的实现类,通过调用接口对象就可以获取 mapper.xml中编写的 sql.
后面 mybatis 和 spring 整合时使用的是这个方案.

实现步骤:

创建一个接口
接口包名和接口名与 mapper.xml 中&lt;- mapper&gt;namespace相同
接口中方法名和 mapper.xml 标签的 id 属性要报持相同
在 mybatis.xml 中使用&lt;-package&gt;进行扫描接口和 mapper.xml


代码实现步骤:

在 mybatis.xml 中&lt;-mappers&gt;下使用&lt;-package&gt;

创建一个接口,接口包名和接口名与 mapper.xml 中namespace相同。接口中方法名和 mapper.xml 标签的 id 属性相同

创建xml文件，获取参数，编写sql namespace 必须和接口全限定路径(包名+类名)一致。id值必须和接口中方法名相同，使用接口绑定可以省略parameterType

通过 ...</div></div></div><div class="recent-post-item"><div class="post_cover right_radius"><a href="/18894.html" title="MyBatis学习-3">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-qdvkdl.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MyBatis学习-3"></a></div><div class="recent-post-info"><a class="article-title" href="/18894.html" title="MyBatis学习-3">MyBatis学习-3</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2019-10-29T06:02:27.000Z" title="发表于 2019-10-29 14:02:27">2019-10-29</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/SSM/">SSM</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/SSM/MyBatis/">MyBatis</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/18894.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/18894.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">MyBatis事务操作功能:从应用程序角度出发,软件具有哪些功能.
业务:完成功能时的逻辑.对应 Service 中一个方法
事务:从数据库角度出发,完成业务时需要执行的 SQL 集合,统称一个事务.
事务回滚.如果在一个事务中某个 SQL 执行事务,希望回归到事务的原点,保证数据库数据的完整性.
在mybatis中默认是关闭了 JDBC 的自动提交功能。每一个 SqlSession 默认都是不自动提交事务.于是利用mybatis进行增删改操作时应该手都动交事务–session.commit()，操作失败发生异常应该回滚事务–seesion.rollback()

openSession(true);自动提交.setAutoCommit(true);

mybatis底层是对JDBC的封装.
JDBC 中 executeUpdate()执行新增,删除,修改的 SQL.返回值 int,表示受影响的行数.
mybatis中&lt;-insert&gt;&lt;-delete&gt;&lt;-update&gt;标签没有 resultType 属性,默认认为返回值都是 int
在 openS ...</div></div></div><div class="recent-post-item"><div class="post_cover left_radius"><a href="/35087.html" title="MyBatis学习-2">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-eorjzk.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MyBatis学习-2"></a></div><div class="recent-post-info"><a class="article-title" href="/35087.html" title="MyBatis学习-2">MyBatis学习-2</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2019-10-27T03:42:39.000Z" title="发表于 2019-10-27 11:42:39">2019-10-27</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/SSM/">SSM</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/SSM/MyBatis/">MyBatis</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/35087.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/35087.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">三种查询方式
.selectList() 返回值为 List&lt;resultType 属性控制&gt; 适用于查询结果都需要遍历的需求 

 

.selectOne() 返回值 Object,适用于返回结果只是变量或一行数据时 

 

.selectMap() 返回值 Map 适用于需要在查询结果中通过某列的值取到这行数据的需求. Map&lt;key,resultType 控制&gt;
 



settings标签
在mybatis全局配置文件中通过settings标签控制 mybatis 全局开关
在mybatis.xml（mybatis配置文件)中开启log4j
必须保证有 log4j.jar
在 src 下有 log4j.properties123&lt;settings&gt;&lt;setting name=&quot;logImpl&quot; value=&quot;LOG4J&quot;/&gt; &lt;/settings&gt;



注意再mybais.xml中的标签顺序
parameterType 属性在XXXMapper.xml中&lt;-sele ...</div></div></div><div class="recent-post-item"><div class="post_cover right_radius"><a href="/34895.html" title="MyBatis学习-1">     <img class="post_bg" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-yjy95k.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MyBatis学习-1"></a></div><div class="recent-post-info"><a class="article-title" href="/34895.html" title="MyBatis学习-1">MyBatis学习-1</a><div class="article-meta-wrap"><span class="post-meta-date"><i class="far fa-calendar-alt"></i><span class="article-meta-label">发表于</span><time datetime="2019-10-27T01:49:51.000Z" title="发表于 2019-10-27 09:49:51">2019-10-27</time></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-inbox"></i><a class="article-meta__categories" href="/categories/SSM/">SSM</a><i class="fas fa-angle-right"></i><a class="article-meta__categories" href="/categories/SSM/MyBatis/">MyBatis</a></span><span class="article-meta"><span class="article-meta__separator">|</span><i class="fas fa-comments"></i><a href="/34895.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/34895.html" itemprop="commentCount"></span></a><span class="article-meta-label"> 条评论</span></span></div><div class="content">
MyBatis 简介MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code，并且改名为MyBatis 。2013年11月迁移到Github。
iBATIS一词来源于“internet”和“abatis”的组合，是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects（DAOs）
作用: 数据访问层框架. 底层是对 JDBC 的封装.
优点之一:使用mybatis时不需要编写实现类,只需要写需要执行的sql命令


MyBatis环境搭建和使用1.导入 jar
2.在src下新建全局配置文件

没有名称和地址要求
在全局配置文件中引入 DTD 或 schema
如果导入dtd后没有提示，可以采用使用本地dtd1234567891011121314151617181920212223&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;&l ...</div></div></div><nav id="pagination"><div class="pagination"><a class="extend prev" rel="prev" href="/page/27/#content-inner"><i class="fas fa-chevron-left fa-fw"></i></a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/27/#content-inner">27</a><span class="page-number current">28</span><a class="page-number" href="/page/29/#content-inner">29</a><span class="space">&hellip;</span><a class="page-number" href="/page/37/#content-inner">37</a><a class="extend next" rel="next" href="/page/29/#content-inner"><i class="fas fa-chevron-right fa-fw"></i></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" data-lazy-src="https://qiniu.codekylin.cn/img/20200807181526.jpg" onerror="this.onerror=null;this.src='https://qiniu.codekylin.cn/github/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">Kylin</div><div class="author-info__description">学习不易，努力努力~</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">362</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">427</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">101</div></a></div></div><a class="button--animated" id="card-info-btn"><i class="fas fa-bookmark"></i><span>加入书签</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/kylincw" target="_blank" title="Github"><i class="iconfont icon-github"></i></a><a class="social-icon" href="tencent://message/?Menu=yes&amp;uin=171346168&amp;Service=300&amp;sigT=45a1e5847943b64c6ff3990f8a9e644d2b31356cb0b4ac6b24663a3c8dd0f8aa12a595b1714f9d45" target="_blank" title="qq"><i class="iconfont icon-qq"></i></a><a class="social-icon" href="https://space.bilibili.com/53836035" target="_blank" title="BiliBili"><i class="iconfont icon-bilibili-line"></i></a><a class="social-icon" href="mailto:zhang171346168@qq.com" target="_blank" title="Email"><i class="iconfont icon-email1"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS"><i class="iconfont icon-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">学习不易，努力努力！</div></div><div class="sticky_layout"><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/56352.html" title="be动词"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/博客封面10.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="be动词"/></a><div class="content"><a class="title" href="/56352.html" title="be动词">be动词</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/36436.html" title="JVM堆内存"><img data-lazy-src="https://qiniu.codekylin.cn/img/20200418115059.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JVM堆内存"/></a><div class="content"><a class="title" href="/36436.html" title="JVM堆内存">JVM堆内存</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/44292.html" title="Java多线程详解"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-eorjzk.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java多线程详解"/></a><div class="content"><a class="title" href="/44292.html" title="Java多线程详解">Java多线程详解</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/40200.html" title="谷粒商城记录"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-6qvvrx.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="谷粒商城记录"/></a><div class="content"><a class="title" href="/40200.html" title="谷粒商城记录">谷粒商城记录</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/27082.html" title="Spring学习-3"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-4x28xo.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Spring学习-3"/></a><div class="content"><a class="title" href="/27082.html" title="Spring学习-3">Spring学习-3</a><time datetime="2022-07-12T11:47:29.799Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div></div></div><div class="card-widget" id="card-newest-comments"><div class="item-headline"><i class="fas fa-bolt"></i><span>最新评论</span></div><div class="aside-list"><span>正在加载中...</span></div></div><div class="card-widget card-categories"><div class="item-headline">
            <i class="fas fa-folder-open"></i>
            <span>分类</span>
            <a class="card-more-btn" href="/categories/" title="查看更多">
    <i class="fas fa-angle-right"></i></a>
            </div>
            <ul class="card-category-list" id="aside-cat-list">
            <li class="card-category-list-item parent"><a class="card-category-list-link" href="/categories/Docker/"><span class="card-category-list-name">Docker</span><span class="card-category-list-count">8</span><i class="fas fa-caret-left "></i></a><ul class="card-category-list child"><li class="card-category-list-item "><a class="card-category-list-link" href="/categories/Docker/CIG/"><span class="card-category-list-name">CIG</span><span class="card-category-list-count">1</span></a></li><li class="card-category-list-item "><a class="card-category-list-link" href="/categories/Docker/compose/"><span class="card-category-list-name">compose</span><span class="card-category-list-count">1</span></a></li></ul></li><li class="card-category-list-item "><a class="card-category-list-link" href="/categories/Elasticsearch/"><span class="card-category-list-name">Elasticsearch</span><span class="card-category-list-count">5</span></a></li><li class="card-category-list-item "><a class="card-category-list-link" href="/categories/English/"><span class="card-category-list-name">English</span><span class="card-category-list-count">1</span></a></li><li class="card-category-list-item parent"><a class="card-category-list-link" href="/categories/Java/"><span class="card-category-list-name">Java</span><span class="card-category-list-count">69</span><i class="fas fa-caret-left "></i></a><ul class="card-category-list child"><li class="card-category-list-item "><a class="card-category-list-link" href="/categories/Java/IO%E6%B5%81/"><span class="card-category-list-name">IO流</span><span class="card-category-list-count">10</span></a></li><li class="card-category-list-item "><a class="card-category-list-link" href="/categories/Java/JDBC/"><span class="card-category-list-name">JDBC</span><span class="card-category-list-count">5</span></a></li></ul></li>
            </ul></div><div class="card-widget card-tags"><div class="item-headline"><i class="fas fa-tags"></i><span>标签</span></div><div class="card-tag-cloud"><a href="/tags/ajax/" style="font-size: 1.15em; color: rgb(29, 46, 14)">ajax</a><a href="/tags/SpringBoot/" style="font-size: 1.45em; color: rgb(40, 91, 26)">SpringBoot</a><a href="/tags/Docker/" style="font-size: 1.3em; color: rgb(68, 166, 82)">Docker</a><a href="/tags/Dockerfile/" style="font-size: 1.15em; color: rgb(1, 93, 85)">Dockerfile</a><a href="/tags/%E5%AE%89%E8%A3%85/" style="font-size: 1.15em; color: rgb(194, 55, 83)">安装</a><a href="/tags/%E5%8D%B8%E8%BD%BD/" style="font-size: 1.15em; color: rgb(43, 190, 86)">卸载</a><a href="/tags/Docker%E7%9A%84%E4%BD%BF%E7%94%A8/" style="font-size: 1.15em; color: rgb(98, 192, 42)">Docker的使用</a><a href="/tags/Portainer/" style="font-size: 1.15em; color: rgb(180, 104, 53)">Portainer</a><a href="/tags/ES6/" style="font-size: 1.15em; color: rgb(185, 98, 89)">ES6</a><a href="/tags/%E7%AE%AD%E5%A4%B4%E5%87%BD%E6%95%B0/" style="font-size: 1.15em; color: rgb(135, 130, 156)">箭头函数</a></div></div><div class="card-widget card-archives"><div class="item-headline"><i class="fas fa-archive"></i><span>归档</span><a class="card-more-btn" href="/archives/" title="查看更多">
    <i class="fas fa-angle-right"></i></a></div><ul class="card-archive-list"><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2022/03/"><span class="card-archive-list-date">2022年03月</span><span class="card-archive-list-count">4</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2022/02/"><span class="card-archive-list-date">2022年02月</span><span class="card-archive-list-count">4</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2022/01/"><span class="card-archive-list-date">2022年01月</span><span class="card-archive-list-count">11</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/12/"><span class="card-archive-list-date">2021年12月</span><span class="card-archive-list-count">4</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/11/"><span class="card-archive-list-date">2021年11月</span><span class="card-archive-list-count">3</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/06/"><span class="card-archive-list-date">2021年06月</span><span class="card-archive-list-count">5</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/05/"><span class="card-archive-list-date">2021年05月</span><span class="card-archive-list-count">2</span></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2021/03/"><span class="card-archive-list-date">2021年03月</span><span class="card-archive-list-count">4</span></a></li></ul></div><div class="card-widget card-webinfo"><div class="item-headline"><i class="fas fa-chart-line"></i><span>网站资讯</span></div><div class="webinfo"><div class="webinfo-item"><div class="item-name">文章数目 :</div><div class="item-count">362</div></div><div class="webinfo-item"><div class="item-name">已运行时间 :</div><div class="item-count" id="runtimeshow" data-publishDate="2019-08-01T16:00:00.000Z"></div></div><div class="webinfo-item"><div class="item-name">本站总字数 :</div><div class="item-count">539.1k</div></div><div class="webinfo-item"><div class="item-name">最后更新时间 :</div><div class="item-count" id="last-push-date" data-lastPushDate="2022-10-12T13:14:25.092Z"></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://qiniu.codekylin.cn/github/img/img20201017211426.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2022 By Kylin</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/"><img class="icp-icon" src="https://img.alicdn.com/tfs/TB1..50QpXXXXX7XpXXXXXXXXXX-40-40.png"><span>湘ICP备2022005420号-1</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>(() => {
  function loadValine () {
    function initValine () {
      let initData = {
        el: '#vcomment',
        appId: 'ClIyIUhj1ue2rcRTsApYCR50-gzGzoHsz',
        appKey: 'ATug9IScYQBHILhKWEqBHYxM',
      }
      
      const valine = new Valine(initData)
    }

    if (typeof Valine === 'function') initValine() 
    else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
  }

  window.pjax ? loadValine() : window.addEventListener('load', loadValine)
})()</script><script>function subtitleType () {
  getScript('https://sdk.jinrishici.com/v2/browser/jinrishici.js').then(() => {
    jinrishici.load(function (result) {
      if (true) {
        var sub = "今日事&#44;今日畢,Never put off till tomorrow what you can do today".length == 0 ? new Array() : "今日事&#44;今日畢,Never put off till tomorrow what you can do today".split(',')
        var content = result.data.content
        var both = sub.unshift(content)
        var typed = new Typed('#subtitle', {
          strings: sub,
          startDelay: 300,
          typeSpeed: 150,
          loop: true,
          backSpeed: 50,
        })
      } else {
        document.getElementById('subtitle').innerHTML = result.data.content
      }
    })
  })
}

if (true) {
  if (typeof Typed === 'function') {
    subtitleType()
  } else {
    getScript('https://cdn.jsdelivr.net/npm/typed.js/lib/typed.min.js').then(subtitleType)
  }
} else {
  subtitleType()
}
</script></div><script src="https://cdn.jsdelivr.net/npm/blueimp-md5@2.17.0/js/md5.min.js"></script><script>window.addEventListener('load', () => {
  const changeContent = (content) => {
    if (content === '') return content

    content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[图片]') // replace image link
    content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[链接]') // replace url
    content = content.replace(/<pre><code>.*?<\/pre>/gi, '[代码]') // replace code
    content = content.replace(/<[^>]+>/g,"") // remove html tag

    if (content.length > 150) {
      content = content.substring(0,150) + '...'
    }
    return content
  }

  const getIcon = (icon, mail) => {
    if (icon) return icon
    let defaultIcon = '?d=robohash'
    let iconUrl = `https://gravatar.loli.net/avatar/${md5(mail.toLowerCase()) + defaultIcon}`
    return iconUrl
  }

  const generateHtml = array => {
    let result = ''

    if (array.length) {
      for (let i = 0; i < array.length; i++) {
        result += '<div class=\'aside-list-item\'>'

        if (true) {
          const name = 'data-lazy-src'
          result += `<a href='${array[i].url}' class='thumbnail'><img ${name}='${array[i].avatar}' alt='${array[i].nick}'></a>`
        }

        result += `<div class='content'>
        <a class='comment' href='${array[i].url}'>${array[i].content}</a>
        <div class='name'><span>${array[i].nick} / </span><time datetime="${array[i].date}">${btf.diffDate(array[i].date, true)}</time></div>
        </div></div>`
      }
    } else {
      result += '没有评论'
    }

    let $dom = document.querySelector('#card-newest-comments .aside-list')
    $dom.innerHTML= result
    window.lazyLoadInstance && window.lazyLoadInstance.update()
    window.pjax && window.pjax.refresh($dom)
  }

  const getComment = () => {
    const serverURL = 'https://cliyiuhj.lc-cn-n1-shared.com'

    var settings = {
      "method": "GET",
      "headers": {
        "X-LC-Id": 'ClIyIUhj1ue2rcRTsApYCR50-gzGzoHsz',
        "X-LC-Key": 'ATug9IScYQBHILhKWEqBHYxM',
        "Content-Type": "application/json"
      },
    }

    fetch(`${serverURL}/1.1/classes/Comment?limit=6&order=-createdAt`,settings)
      .then(response => response.json())
      .then(data => {
        const valineArray = data.results.map(function (e) {
          return {
            'avatar': getIcon(e.QQAvatar, e.mail),
            'content': changeContent(e.comment),
            'nick': e.nick,
            'url': e.url + '#' + e.objectId,
            'date': e.updatedAt,
          }
        })
        saveToLocal.set('valine-newest-comments', JSON.stringify(valineArray), 10/(60*24))
        generateHtml(valineArray)
      }).catch(e => {
        const $dom = document.querySelector('#card-newest-comments .aside-list')
        $dom.innerHTML= "无法获取评论，请确认相关配置是否正确"
      }) 
  }

  const newestCommentInit = () => {
    if (document.querySelector('#card-newest-comments .aside-list')) {
      const data = saveToLocal.get('valine-newest-comments')
      if (data) {
        generateHtml(JSON.parse(data))
      } else {
        getComment()
      }
    }
  }

  newestCommentInit()
  document.addEventListener('pjax:complete', newestCommentInit)
})</script><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script></div></body></html>